package views;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.Date;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import common.Contexto;

import business.interfaces.ISocio;
import controllers.IErrorObserver;
import controllers.SociosController;
import data.entities.Cliente;
import data.entities.Socio;
import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;

/**
 * Pantalla de socio que permite cargar los datos de un nuevo socio o desplegar
 * la informaci�n de uno existente
 * 
 */
@SuppressWarnings("serial")
public class SocioPanel extends JPanel implements IErrorObserver {
	
	private JLabel nroDocL, nombreL, apellidoL, emailL, fechaNacL, sexoL, telefonoL, domicilioL, codigoPostalL;
	
	private JTextField nroDocT, nombreT, apellidoT, emailT, telefonoT, domicilioT, codigoPostalT;
	
	private JDatePickerImpl datePicker;
	private UtilDateModel dateModel;

	private JComboBox sexoC;
	
	private JButton guardarB, volverB;

	/* alterna el modo lectura o escritura de la pantalla */
	private boolean writeMode;
	
	
	private SociosController controller;

	/**
	 * main de prueba para la pantalla de socio
	 * @param args
	 */
	public static void main(String[] args) {
		new SocioPanel(false).showPanel();
	}
	
	public SocioPanel(boolean writeMode) {
		this.writeMode = writeMode;
		this.controller = new SociosController();
		
		this.controller.agregarErrorObserver(this);
		
		initGui();
		layoutComponents();
		initActions();
	}

	private boolean guardarSocio() {
		String dni = nroDocT.getText();
		String nombre = nombreT.getText() + " " + apellidoT.getText();
		Date fechaNac = (Date) datePicker.getModel().getValue();
		String domicilio = domicilioT.getText();
		String telefono = telefonoT.getText();
		String email = emailT.getText();
		
		return controller.guardarSocio(dni, nombre, fechaNac, domicilio, telefono, email);
	}
	
	/* TODO: Ponerlo como private cuando se remueva el static main */	
	@SuppressWarnings("deprecation")
	public void setSocio(ISocio socio) {
		nombreT.setText(socio.getNombre());
		nroDocT.setText(socio.getDni());
		telefonoT.setText(socio.getTelefono());
		domicilioT.setText(socio.getDomicilio());
		emailT.setText(socio.getEmail());
		
		Date d = socio.getFechaNacimiento();
		
		dateModel.setDate(d.getYear(), d.getMonth(), d.getDay());
		dateModel.setSelected(true);
	}
	
	public void notificarError(String error) {
		Contexto.displayErrorMessage(this, error);
	}
	
	private void initGui() {
		nroDocL = new JLabel("* Nro doc.");
		nombreL = new JLabel("* Nombre");
		apellidoL = new JLabel("* Apellido");
		emailL = new JLabel("Email");
		fechaNacL = new JLabel("*Fecha nac.");
		sexoL = new JLabel("Sexo");
		telefonoL = new JLabel("* Telefono");
		domicilioL = new JLabel("Domicilio");
		codigoPostalL = new JLabel("Codigo Postal");
		String[] sexoCValues = new String[]{"Masculino", "Femenino"};
		sexoC = new JComboBox(sexoCValues);
		volverB = new JButton("Volver");
		guardarB = new JButton("Guardar");
		
		nroDocT = new JTextField(10);
		nombreT = new JTextField(10);
		apellidoT = new JTextField(10);
		emailT = new JTextField(10);
		dateModel = new UtilDateModel();
		JDatePanelImpl datePanel = new JDatePanelImpl(dateModel);
		datePicker = new JDatePickerImpl(datePanel);
		telefonoT = new JTextField(10);
		domicilioT = new JTextField(10);
		codigoPostalT = new JTextField(10);
		
		if(!writeMode) {
			nroDocT.setEnabled(false);
			nombreT.setEnabled(false);
			apellidoT.setEnabled(false);
			emailT.setEnabled(false);
			datePicker.setEnabled(false);
			telefonoT.setEnabled(false);
			domicilioT.setEnabled(false);
			codigoPostalT.setEnabled(false);
			sexoC.setEnabled(false);
		}
	}

	private void layoutComponents() {
		this.setLayout(new GridBagLayout());
		
		GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.anchor = GridBagConstraints.WEST ;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(0, 2, 2, 4);
        add(nroDocL, c);

        c.gridy = GridBagConstraints.RELATIVE;
        add(nombreL, c);
        add(apellidoL, c);
        add(emailL, c);
        
        c.gridx = 1;
        c.gridy = 0;
        c.anchor = GridBagConstraints.WEST ;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(0, 2, 2, 4);
        add(nroDocT, c);

        c.gridy = GridBagConstraints.RELATIVE;
        add(nombreT, c);
        add(apellidoT, c);
        add(emailT, c);
        
        c.gridx = 2;
        c.gridy = 0;
        c.anchor = GridBagConstraints.WEST ;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(0, 2, 2, 4);
        add(fechaNacL, c);

        c.gridy = GridBagConstraints.RELATIVE;
        add(sexoL, c);
        add(telefonoL, c);
        add(domicilioL, c);
        add(codigoPostalL, c);
        
        c.gridx = 3;
        c.gridy = 0;
        c.anchor = GridBagConstraints.WEST ;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(0, 2, 2, 4);
        add(datePicker, c);

        c.gridy = GridBagConstraints.RELATIVE;
        add(sexoC, c);
        add(telefonoT, c);
        add(domicilioT, c);
        add(codigoPostalT, c);
        
        c.gridx = 1;
        c.gridy = 7;
        c.insets = new Insets(20, 0, 10, 0);
        
        if(writeMode) {
        	add(guardarB, c);
        }
        
        c.gridx = 2;
        add(volverB, c);

	}
	
	private void initActions() {
		guardarB.setAction(new AbstractAction("Guardar"){
			@Override
			public void actionPerformed(ActionEvent e) {
				if(validateFields()) {
					boolean guardaSocio = guardarSocio();
					if(guardaSocio){
						clearFields();
						SwingUtilities.windowForComponent(SocioPanel.this).dispose();
						Contexto.displayFeedbackMessage(SocioPanel.this, "El socio fue guardado con exito");
					}
					
				}
			}			
		});
		
		volverB.setAction(new AbstractAction("Volver"){
			@Override
			public void actionPerformed(ActionEvent e) {
				SwingUtilities.windowForComponent(SocioPanel.this).dispose();
				clearFields();
			}			
		});
	}
	
	private boolean validateFields() {
		try {
			Integer.parseInt(nroDocT.getText()); 
		} catch(NumberFormatException e) {
			notificarError("El numero de documento, debe ser un valor numerico");
			return false;
		}
		
		String nombreV = nombreT.getText();
		String apellidoV = apellidoT.getText();
		String telefonoV = telefonoT.getText();

		if(nombreV.length() == 0 || apellidoV.length() == 0 || telefonoV.length() == 0){
			notificarError("Por favor complete todos los campos obligatorios marcados con *");
			return false;
		}
		
		return true;
	}

	private void clearFields() {
		nombreT.setText("");
		telefonoT.setText("");
		domicilioT.setText("");
		codigoPostalT.setText("");
		emailT.setText("");
		apellidoT.setText("");
		nroDocT.setText("");
		sexoC.setSelectedIndex(0);
		datePicker.getModel().setValue(null);
	}
	
	public void showPanel() {
		final JFrame mainFrame = new JFrame();
        mainFrame.setTitle("Nuevo Socio");
        mainFrame.getContentPane().add(this);
        mainFrame.setPreferredSize(new Dimension(700,340));
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.pack();
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
	}
}
